<template>
    <div class="address-book">
        <!-- <header>Address book</header> -->

        <!-- 贴顶导航 -->
        <UserFixedHead title="Address book" />

        <!-- 初始化 -->
        <UxIniting v-if="!inited" />

        <template v-else>
            <h2>Address book</h2>
            <p v-if="list.length == 0">Here you can save frequently used addresses for future use.</p>
            <p v-else>You cannot save more than 4 addresses in your address book.</p>

            <!-- 空数据 -->
            <div class="address-empty" v-if="list.length == 0">
                <!-- <span>You cannot save more than 4 addresses in your address book.</span> -->
                <figure><img src="@/assets/images/setting/setting-address-empty.png" alt=""></figure>
                <UserSearchButton size="large" shape="solid" name="Add address" icon="user-template-new" @click="toEdit()" />
            </div>

            <div class="address-list" v-else>

                <ul>
                    <li v-for="item in list" :key="item.id">
                        <h3 :title="item.first_name">{{ item.first_name }}</h3>

                        <p>
                            <img src="@/assets/images/setting/setting-address-phone.png" alt="">
                            <span>Phone:</span>
                            <strong v-text="item.phone"></strong>
                        </p>
                        <p>
                            <img src="@/assets/images/setting/setting-address-email.png" alt="">
                            <span>Email:</span>
                            <strong v-text="item.email"></strong>
                        </p>
                        <p>
                            <img src="@/assets/images/setting/setting-address-address.png" alt="">
                            <span>Address1:</span>
                            <strong>
                                <em v-text="item.street"></em>
                                <em v-text="[item.city,item.state,item.country].filter(i=>i).join(',')"></em>
                            </strong>
                        </p>
                        <p v-if="item.district != ''">
                            <img src="@/assets/images/setting/setting-address-address.png" alt="">
                            <span>Address2:</span>
                            <strong v-text="item.district"></strong>
                        </p>
                        <p>
                            <img src="@/assets/images/setting/setting-address-postcode.png" alt="">
                            <span>Post code:</span>
                            <strong v-text="item.post_code"></strong>
                        </p>

                        <cite>
                            <button @click="toEdit(item)"><svg-icon name="edit" /></button>
                            <button @click="dialog_remove = item.id"><svg-icon name="remove" /></button>
                        </cite>

                    </li>

                    <li class="address-list-add" @click="toEdit()" v-if="list.length < 4">
                        <svg-icon name="user-template-new" />
                        <span>Add Address</span>
                    </li>
                </ul>

            </div>

            <UxLoading2 :loading="loading" />

        </template>

        <!-- 删除 -->
        <UxDialog :visible="dialog_remove" @close="dialog_remove = null">
            <div class="dialog-remove">
                <img src="@/assets/images/setting/dialog-address-delete.png" alt="">
                <p>Are you sure to delete this address?</p>
                <fieldset>
                    <button type="primary" @click="doDel()">Yes</button>
                    <button @click="dialog_remove = null">NO</button>
                </fieldset>
                <UxLoading2 :loading="loading" />
            </div>
        </UxDialog>

        <UxDialog :visible="dialog_edit" @close="dialog_edit = null">
            <div class="dialog-edit">
                <h2 v-text="dialog_edit && dialog_edit.id ? 'Edit address' : 'Add address'"></h2>
                <CommonAddressForm v-model="dialog_edit" @validate="onAddressValidate($event)" ref="address-form" />
                <fieldset>
                    <button v-if="dialog_edit && dialog_edit.id" @click="doEditUpdate($event)" :class="{disabled:dialog_forbid}" type="primary">Modify</button>
                    <button v-else :class="{disabled:dialog_forbid}" @click="doEditUpdate($event)" type="primary">Save</button>
                </fieldset>
                <UxLoading2 :loading="loading" />
            </div>
        </UxDialog>

    </div>
</template>
<script>

// let formRule = {
//     checkName: (rule, value, callback) => {
//         if (value === "") {
//             callback(new Error("请输入名字"));
//         } else {
//             callback();
//         }
//     },
//     checkEmail: (rule, value, callback) => {
//         if (value === "") {
//             callback(new Error("请输入邮箱"));
//         } else {
//             callback();
//         }
//     },
//     checkCountry: (rule, value, callback) => {
//         if (value === "") {
//             callback(new Error("请输入国家"));
//         } else {
//             callback();
//         }
//     },
//     checkAddress: (rule, value, callback) => {
//         if (value === "") {
//             callback(new Error("请输入地址"));
//         } else {
//             callback();
//         }
//     },
//     checkCity: (rule, value, callback) => {
//         if (value === "") {
//             callback(new Error("请输入城市"));
//         } else {
//             callback();
//         }
//     },
//     checkPostcode: (rule, value, callback) => {
//         if (value === "") {
//             callback(new Error("请输入邮编"));
//         } else {
//             callback();
//         }
//     },
// };

export default {
    name: "address-book",
    layout: "layout-user",
    data () {

        return {
            inited: false,
            loading: false,
            list: [],
            dialog_remove: null,
            dialog_edit: null,
            dialog_forbid: true,
            dialog_validate: false,
            dialog_cache: {},
        };
    },
    watch: {
        // dialog_edit: {
        //     deep: true,
        //     handler () {
        //         this.checkForbid()
        //     }
        // }
    },
    methods: {
        async getAddress () {
            this.loading = true;
            let res = await this.$http("address.search");

            if (res.code == 0) {
                this.loading = false;
                this.list = res.data;
            } else {
                this.loading = false;
                this.$uxMessage({
                    message: "Failed to get user address",
                    type: "warning",
                });
            }
        },
        async doDel () {
            this.loading = true;
            let res = await this.$http("address.remove", this.dialog_remove);
            if (res.code == 0) {
                this.dialog_remove = null;
                this.getAddress().then(() => this.dialog_remove = null)
                this.$uxMessage.success("Address deleted successfully");
            } else {
                this.$uxMessage.warning(res.msg);
                this.loading = false;
                this.dialog_remove = null;
            }
        },

        async doEditUpdate (event) {

            if (this.dialog_forbid) {
                // 触发检查
                const target = this.$refs['address-form']
                target && target.tipsValidator().then(res => { }).catch(err => { });
            } else {

                const id = this.dialog_edit.id
                const req = {
                    first_name: this.dialog_edit.first_name,
                    phone: this.dialog_edit.phone,
                    email: this.dialog_edit.email,
                    country_code: this.dialog_edit.country_code,
                    country: this.dialog_edit.country,
                    state: this.dialog_edit.state,
                    street: this.dialog_edit.street,
                    district: this.dialog_edit.district,
                    city: this.dialog_edit.city,
                    post_code: this.dialog_edit.post_code,
                };

                let result = null;
                this.loading = true;

                if (id) {
                    result = await this.$http("address.update/" + id, req);
                } else {
                    result = await this.$http("address.insert", req);
                }

                if (result.code == 0) {
                    this.$uxMessage({
                        offset: 40,
                        message: id ? 'Address changed successfully' : "Address added successfully",
                        type: "success",
                    });
                    this.getAddress().then(() => this.dialog_edit = null)
                } else {

                    this.loading = false;
                    this.$uxMessage({
                        offset: 40,
                        message: id ? "Failed to change address" : "Failed to add address",
                        type: "warning",
                    });
                }
            }
        },

        doEditCancel (event) {
            event.stopPropagation();
            event.preventDefault();
            this.$router.go(-1);
        },

        checkForbid () {
            if (!this.dialog_validate) {
                this.dialog_forbid = true;
            } else if (this.dialog_cache && this.dialog_edit) {
                this.dialog_forbid = Object.keys(this.dialog_cache).findIndex(key => this.dialog_cache[key] != this.dialog_edit[key]) < 0
            } else {
                this.dialog_forbid = false
            }
        },

        toEdit (item) {
            const edit = {
                city: "",
                country: "",
                country_code: "",
                district: "",
                email: "",
                first_name: "",
                id: '',
                phone: "",
                post_code: "",
                state: "",
                street: "",
            }

            item && Object.keys(edit).map(key => edit[key] = item[key])
            this.dialog_cache = { ...edit }
            this.dialog_validate = false;
            this.dialog_edit = edit

        },

        onAddressValidate (event) {
            this.dialog_validate = !event
            this.checkForbid()
        }
    },
    created () {
        process.client && this.getAddress().then(() => {
            this.inited = true
        });
    },
};
</script>
<style lang="scss" scoped>
.address-book {
    display: flex;
    flex-direction: column;
    position: relative;
    & > .loading {
        position: fixed;
        left: 228px;
        top: 0;
        bottom: 0;
        right: 0;
    }

    & > .initing {
        flex: 1;
        width: 100%;
    }

    & > h2 {
        display: flex;
        align-items: center;
        font-size: 36px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 40px;
    }

    & > p {
        margin-top: 24px;
        font-size: 16px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #212121;
        line-height: 20px;
    }
}

.address-empty {
    margin-top: 14px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    figure {
        position: relative;
        width: 100%;
        &::before {
            content: '';
            display: block;
            padding-bottom: 40%;
        }
        img {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
        }
    }
    span {
        margin-top: 8px;
        font-size: 16px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #212121;
        line-height: 20px;
    }

    .user-search-button {
        margin-top: 24px;
        width: 160px;
        height: 40px;
    }
}

.address-list {
    position: relative;
    ul {
        display: flex;
        flex-wrap: wrap;
        margin: 16px -8px 0;
    }
    li {
        width: calc(50% - 16px);
        margin: 8px;
        background: #ffffff;
        border-radius: 8px;
        border: 1px solid #e6e6e6;
        position: relative;
        box-sizing: border-box;
        padding: 38px 38px 40px;

        h3 {
            font-size: 24px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #000000;
            line-height: 26px;
            margin-bottom: 24px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin-right: 72px;
        }

        p {
            display: flex;
            & + p {
                margin-top: 12px;
            }
            img {
                width: 16px;
                height: 16px;
            }
            span {
                margin-left: 4px;
                width: 68px;
                height: 16px;
                font-size: 14px;
                font-family: Roboto-Regular, Roboto;
                font-weight: 400;
                color: #555555;
                line-height: 16px;
            }
            strong {
                margin-left: 12px;
                font-size: 14px;
                font-family: Roboto-Regular, Roboto;
                font-weight: 400;
                color: #000000;
                line-height: 16px;
                display: block;
                white-space: normal;
                word-break: break-word;
                em {
                    display: block;
                }

                em + em {
                    margin-top: 8px;
                }
            }
        }

        cite {
            position: absolute;
            display: flex;
            right: 32px;
            top: 35px;
            &::before {
                content: '';
                position: absolute;
                left: 50%;
                top: 50%;
                width: 1px;
                height: 8px;
                transform: translate(-50%, -50%);
                background: #d8d8d8;
            }

            button {
                width: 32px;
                height: 32px;
                padding: 0;
                border: none;
                border-radius: 4px;
                display: flex;
                align-items: center;
                justify-content: center;

                svg {
                    width: 18px;
                    height: 18px;
                    color: #757575;
                }

                & + button {
                    margin-left: 6px;
                    svg {
                        width: 20px;
                        height: 20px;
                    }
                }
                &:hover {
                    background-color: rgba(#000, 0.06);
                    svg {
                        color: #000;
                    }
                }
            }
        }
    }

    .address-list-add {
        border-style: dashed;
        display: flex;
        align-items: center;
        justify-content: center;
        min-height: 250px;
        transition: all 0.2s;
        cursor: pointer;
        color: #555555;
        border-color: #b3b3b3;
        background-color: transparent;

        & > svg {
            width: 20px;
            height: 20px;
        }
        & > span {
            margin-left: 6px;
            font-size: 18px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            line-height: 20px;
        }

        &:hover {
            background: #ffffff;
            border-color: transparent;
            box-shadow: 0px 4px 6px 0px rgba(0, 0, 0, 0.08);
            color: #ea4c89;
        }
    }
}

.dialog-remove {
    width: 320px;
    height: 414px;
    padding: 66px 14px 14px;
    box-sizing: border-box;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;

    img {
        width: 80px;
        height: 80px;
    }
    p {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        font-size: 16px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #000000;
        line-height: 22px;
    }
    fieldset {
        width: 100%;
        display: flex;
        flex-direction: column;
        button {
            height: 38px;
            margin-top: 8px;
        }
    }
}

.dialog-edit {
    width: 764px;

    & > h2 {
        font-size: 24px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 26px;
        padding: 28px 32px 24px;
    }

    .address-form {
        margin: 0 22px;
        &::v-deep .el-form-item {
            padding-left: 10px;
            padding-right: 10px;
        }
    }

    fieldset {
        border-top: 1px solid #e6e6e6;
        display: flex;
        justify-content: center;
        padding: 12px;
        button {
            width: 140px;
        }
    }
}
</style>
